import {
	BASE_HTTP_REQUEST_URL,
	HTTP_REQUEST_URL,
	HEADER
}
from '@/config/app.js'
import { concatUrl , toLogin } from './utils.js'
import store from '../store'

// 封装请求
function apiRequest(url = '', method = 'GET', data = {}, istoken = true, cond) {
	let header;
	if (istoken) {
		let token = store.getters.getToken;
		header = {
			...HEADER,
			'X-Token': token
		}
	} else {
		header = HEADER;
	}
	console.log(HTTP_REQUEST_URL + url + concatUrl(cond));
	return new Promise((resolve, reject) => {
		uni.request({
			url: HTTP_REQUEST_URL + url + concatUrl(cond),
			data: data,
			header: header,
			method: method,
			timeout: 15000,
			success: (res) => {
				console.log(res);
				if (res.data.status == 200)
					resolve(res.data.data);
				else if ([410000, 410001, 410002, 40000, 400].indexOf(res.data.status) !== -1) {
					reject(res.data);
					toLogin();
				} else if (res.data.status == 501) {
					uni.reLaunch({
						url: '/pages/error/index'
					})
					reject(res.data);
				} else {
					reject(res.data.message || '系统错误');
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

// 封装请求
function baseRequest(url = '', method = 'GET', data = {}, istoken = true, cond) {
	let header;
	if (istoken) {
		let tokenInfo = store.getters.getToken;
		header = {
			...HEADER,
			'X-Token': tokenInfo
		}
	} else {
		header = HEADER;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_HTTP_REQUEST_URL + url + concatUrl(cond),
			data: data,
			header: header,
			method: method,
			timeout: 15000,
			success: (res) => {
				console.log(res);
				if (res.data.status == 200)
					resolve(res.data.data);
				else if ([410000, 410001, 410002, 40000, 400].indexOf(res.data.status) !== -1) {
					reject(res.data);
				} else if (res.data.status == 501) {
					uni.reLaunch({
						url: '/pages/error/index'
					})
					reject(res.data);
				} else {
					reject(res.data.message || '系统错误');
				}
			},
			fail: (err) => {
				reject('请求失败');
				console.log(err);
			}
		});
	})
}

const request = {};

['get','post'].forEach((method) => {
	request[method] = (api, data, istoken, cond) => apiRequest(api, method, data, istoken, cond)
});

['baseget','basepost'].forEach((method) => {
	request[method] = (api, data, istoken, cond) => baseRequest(api, method, data, istoken, cond)
})

export default request;
